<template>
  <view class="c-upload">
    <view class="flex-center" style="flex-wrap: wrap">
      <view
        v-if="showAdd && list.length < max"
        class="add flex-box"
        :style="itemStyles"
        @click.stop="chooseImage"
      >
        <slot name="add">
          <view>
            <server-image class="icon-upload" :name="addIcon"></server-image>
            <view class="note">{{ tips }}</view>
          </view>
        </slot>
      </view>
      <view
        v-for="(item, index) in list"
        :key="index"
        class="item"
        :style="itemStyles">
        <c-image
          :key="item"
          :class="['img',imgClass]"
          :mode="mode"
          :src="item"
          @click="preview(item)"
        ></c-image>
        <view v-if="!readonly" class="del-warp" @click="del(index)">
          <server-image class="icon-delete" :name="delIcon"></server-image>
        </view>
      </view>
    </view>

    <c-image-preview v-if="bigImg" :src="bigImg" @click="bigImg = ''"></c-image-preview>
  </view>
</template>

<script>
import cImagePreview from './c-image-preview';
import config from '@/common/config';
import { uniChooseImage } from '@/common/utils';
let { baseUrl, shopApiUrl, type } = config;
import { encryptPassword, uuid } from '@/common/utils';

export default {
  name: 'c-upload',
  components: {
    cImagePreview,
  },
  props: {
    readonly: {
      type: Boolean,
      default: false,
    },
    addIcon: {
      type: String,
      default: 'add_icon.png',
    },
    delIcon: {
      type: String,
      default: 'auditIconUploadDelete.png',
    },
    canPreview: {
      type: Boolean,
      default: true,
    },
    canDelete: {
      type: Boolean,
      default: true,
    },
    showAdd: {
      type: Boolean,
      default: true,
    },
    value: {
      type: Array,
      default: () => [],
    },
    max: {
      type: [Number, String],
      default: 1,
    },
    itemStyles: {
      type: [Object, String],
      default: '',
    },
    tips: {
      type: String,
      default: '',
    },
    extraData: {
      type: Object,
      default: () => ({}),
    },
    isAudit: {
      type: Boolean,
      default: false,
    },
    maxSize: {
      type: Number,
      default: 100*1024,
    },
    imgClass: {
      type: String,
      default: '',
    },
    mode: {
      type: String,
      default: 'aspectFill',
    },
  },
  data() {
    return {
      list: [],
      bigImg: '',
      resList: [],
    };
  },
  computed: {
    maxSizeByte() {
      return this.maxSize * 1024;
    },
  },
  watch: {
    value: function (val) {
      this.list = val;
    },
    list: function (val) {
      this.$emit('input', val);
    },
  },
  created() {
    this.list = this.value;
  },
  methods: {
    // 新签名md5(key+timestamp)
    newSign(params) {
      params.sign = encryptPassword(params.timestamp, 'SKService').toUpperCase();
    },
    preview(path) {
      if (this.canPreview) {
        this.bigImg = path;
      }
    },
    del(index) {
      this.list = this.list.splice(index, 1);
    },
    chooseImage() {
      const vm = this;
      if (vm.readonly) return;
      const max = vm.max - vm.list.length;
      let index = 0;
      let tempFilePaths = [];

      // 跨域
      shopApiUrl = (type == 1 ? '/api/' : shopApiUrl);
      baseUrl = (type == 1 ? '/api/' : baseUrl);


      let formData = {
        ...vm.extraData,
        // 当前时间
        timestamp: Date.now()
      }
      // 新签名
      this.newSign(formData);

      // let uploadApi = vm.isAudit
      //   ? shopApiUrl + 'api_func_uploadfile'+'?sign='+formData.sign
      //   : baseUrl + 'api_func_uploadfile'+'?sign='+formData.sign;
      let uploadApi = vm.isAudit
        ? shopApiUrl + 'api_func_uploadfile'
        : baseUrl + 'api_func_uploadfile';

      const uploadCompressedImage = (filePath,chooseImageRes,isBigFile=false) =>{

      	let extraData = vm.extraData
      	if(isBigFile){
      	  extraData = {
      		...vm.extraData,
      		isBigFile: isBigFile
      	  }
      	}

      	uni.uploadFile({
      	  url: uploadApi,
      	  filePath: filePath,
      	  name: 'file',
      	  formData: extraData,
      	  // formData: {
      	  //   'file': JSON.stringify(formData) // 将 JSON 对象转换为字符串
      	  // },
      	  // header: {
      	  //   'content-type': 'application/json;charset=UTF-8' // 设置请求的 header
      	  // },
      	  success: (res) => {
      	    console.log(res);
      	    let { code,msg:message='',data:{
      	      url = ''
      	    } } = JSON.parse(res.data);
      	    if (code != 0){
      	      this.showMessage({ title: message });
      	      return;
      	    };
      	    if (url) {
      	      vm.list = vm.list.concat(url);
      	      let arr = [...vm.resList];
      	      arr[vm.list.length - 1] = url;
      	      vm.resList = arr;
      	      index++;
      	      uploadImage();
      	    }
      	  },
      	});
      }

      const uploadImage = (chooseImageRes) => {
      	if (index < tempFilePaths.length && index < max) {
      		const filePath = tempFilePaths[index];

          // uni.getFileSystemManager().getFileInfo()替换uni.getFileInfo() API
          let fileSystemManager = uni.getFileInfo;
          if (vm.isGetFileSystemManagerSupported()) {
            // console.log('当前环境支持getFileSystemManager API');
            fileSystemManager = uni.getFileSystemManager().getFileInfo;
            // 使用fileSystemManager进行文件操作
          } else {
            // console.log('当前环境不支持getFileSystemManager API');
          }
      		// 获取图片文件大小
          // uni.getFileInfo({
      		fileSystemManager({
      			filePath: filePath,
      			success: (fileInfo) => {
      				const fileSize = fileInfo.size; // 图片文件大小，单位为B
              // console.log('fileSize',fileSize)
      				// 判断图片大小是否超过100KB
      				if (fileSize > 100 * 1024) {
      					//#ifdef H5
      					//h5压缩图片
      					// const targetSizeKB = 150; // 设置目标文件大小，单位为KB，根据需求调整
      					vm.compressH5(chooseImageRes.tempFiles[0],config.targetSizeKB).then(file => {
      						console.log('file 222 = ', file)
      						uploadCompressedImage(file,chooseImageRes,true);
      						}).catch(err => {
      							console.log('catch', err)
      						})
      					//#endif
      					//#ifdef APP-PLUS || MP-WEIXIN
      					// 如果超过3072KB，进行压缩
      					uni.compressImage({
      						src: filePath,
      						quality: 10, // 设置压缩质量（0-100）- 根据需求进行调整
      						success: (compressRes) => {
      							// 压缩成功后的逻辑
      							uploadCompressedImage(compressRes.tempFilePath,chooseImageRes);
      						},
      						fail: (err) => {
      							console.error('压缩图片失败:', err);
      							uni.showToast({
      								title: "压缩图片失败",
      								icon: 'none'
      							});
      						}
      					});
      					//#endif
      				} else {
      					// 如果未超过3072KB，直接上传原图
      					uploadCompressedImage(filePath,chooseImageRes);
      				}
      			},
      			fail: (err) => {
      				// console.error('获取文件信息失败:', err);
      				// uni.showToast({
      				// 	title: "获取文件信息失败",
      				// 	icon: 'none'
      				// });
      				// 如果获取文件信息失败，直接上传原图
      				uploadCompressedImage(filePath,chooseImageRes);
      			}
      		});


      	} else {
      		uni.hideLoading();
      		vm.$emit('complete', vm.resList);
      	}
      };

      uniChooseImage({
        count: max,
        sizeType: ['original', 'compressed'],
        // sourceType: ['album'],
        sourceType: ['album', 'camera'],
        success: async (chooseImageRes) => {
          const tempFiles = chooseImageRes.tempFiles.filter((v) =>
            this.maxSizeByte ? v.size <= this.maxSizeByte : true
          );
          if (tempFiles.length !== chooseImageRes.tempFiles.length)
            await this.showMessage({
              title: `上传图片大小不能超过${this.maxSize}kb`,
              duration: 1500,
            });
          tempFilePaths = tempFiles.map((v) => v.path); // chooseImageRes.tempFilePaths;
          if (tempFilePaths.length > max) tempFilePaths = tempFilePaths.slice(0, max);
          if (!tempFilePaths.length) return;
          uni.showLoading({ title: '上传中...' });
          uploadImage();
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.add,
.item {
  box-sizing: border-box;
  width: 160rpx;
  height: 160rpx;
  background: #f5f5f5;
  //border: 1px dotted #BCBCBC;
  border-radius: 10rpx;
  margin-right: 60rpx;
  margin-bottom: 40rpx;
  position: relative;
  &:nth-child(3n) {
    margin-right: 0;
  }
}

.icon-upload {
  width: 60rpx;
  height: 60rpx;
  display: block;
  margin: 0 auto;
}

.img {
  width: 100%;
  height: 100%;
  display: block;
  //background: #808080;
  background: #f3f4f6;
}

.icon-delete {
  width: 36rpx;
  height: 36rpx;
  display: block;
  overflow: hidden;
  position: absolute;
  right: 28rpx;
  top: 28rpx;
}

.note {
  margin-top: 10rpx;
  font-size: 24rpx;
  font-weight: 400;
  color: rgba(188, 188, 188, 1);
  text-align: center;
}

.del-warp {
  width: 88rpx;
  height: 88rpx;
  /*background-color: #0A98D5;*/
  position: absolute;
  right: -44rpx;
  top: -44rpx;
}
</style>
